<template>
  <div class="profile-container">
    <a-row :gutter="24">
      <!-- 左侧用户信息 -->
      <a-col :xs="24" :lg="8">
        <a-card class="user-info-card">
          <div class="user-avatar-section">
            <a-avatar 
              :src="userInfo?.avatar" 
              :size="120"
              class="user-avatar"
            >
              {{ userInfo?.nickname?.charAt(0) || 'U' }}
            </a-avatar>
            <a-button 
              type="link" 
              @click="showAvatarModal = true"
              class="change-avatar-btn"
            >
              更换头像
            </a-button>
          </div>
          
          <div class="user-details">
            <h2>{{ userInfo?.nickname }}</h2>
            <p class="username">@{{ userInfo?.username }}</p>
            <p class="email">{{ userInfo?.email }}</p>
            <p class="role">角色：{{ getRoleText(userInfo?.role) }}</p>
            <p class="join-date">
              加入时间：{{ formatDate(userInfo?.createdAt) }}
            </p>
          </div>
        </a-card>

        <!-- 用户统计 -->
        <a-card title="数据统计" class="stats-card">
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-number">{{ userStats.postCount }}</div>
              <div class="stat-label">文章数</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ userStats.likeCount }}</div>
              <div class="stat-label">获赞数</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ userStats.viewCount }}</div>
              <div class="stat-label">浏览量</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ userStats.commentCount }}</div>
              <div class="stat-label">评论数</div>
            </div>
          </div>
        </a-card>
      </a-col>

      <!-- 右侧编辑表单 -->
      <a-col :xs="24" :lg="16">
        <a-card title="编辑个人信息" class="edit-form-card">
          <a-form
            :model="editForm"
            :rules="editRules"
            @finish="handleUpdateProfile"
            layout="vertical"
          >
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="昵称" name="nickname">
                  <a-input 
                    v-model:value="editForm.nickname"
                    placeholder="请输入昵称"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="邮箱" name="email">
                  <a-input 
                    v-model:value="editForm.email"
                    placeholder="请输入邮箱"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-form-item label="个人简介" name="bio">
              <a-textarea 
                v-model:value="editForm.bio"
                placeholder="介绍一下自己吧..."
                :rows="4"
              />
            </a-form-item>

            <a-form-item label="个人网站" name="website">
              <a-input 
                v-model:value="editForm.website"
                placeholder="https://example.com"
              />
            </a-form-item>

            <a-form-item>
              <a-space>
                <a-button 
                  type="primary" 
                  html-type="submit"
                  :loading="updateLoading"
                >
                  保存修改
                </a-button>
                <a-button @click="resetForm">
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 最近文章 -->
        <a-card title="我的文章" class="posts-card">
          <a-spin :spinning="postsLoading">
            <div v-if="userPosts.length === 0" class="empty-posts">
              <a-empty description="暂无文章">
                <a-button type="primary" @click="$router.push('/write')">
                  写第一篇文章
                </a-button>
              </a-empty>
            </div>
            <div v-else class="posts-list">
              <div 
                v-for="post in userPosts" 
                :key="post.id"
                class="post-item"
              >
                <div class="post-content">
                  <h4 class="post-title">{{ post.title }}</h4>
                  <p class="post-excerpt">{{ post.excerpt }}</p>
                  <div class="post-meta">
                    <span>{{ formatDate(post.createdAt) }}</span>
                    <span>{{ post.views || 0 }} 次阅读</span>
                  </div>
                </div>
                <div class="post-actions">
                  <a-button 
                    type="link" 
                    size="small"
                    @click="$router.push(`/post/${post.id}`)"
                  >
                    查看
                  </a-button>
                  <a-button 
                    type="link" 
                    size="small"
                    @click="$router.push(`/edit/${post.id}`)"
                  >
                    编辑
                  </a-button>
                </div>
              </div>
            </div>
          </a-spin>
        </a-card>
      </a-col>
    </a-row>

    <!-- 头像上传模态框 -->
    <a-modal
      v-model:open="showAvatarModal"
      title="更换头像"
      @ok="handleAvatarUpdate"
      :confirm-loading="avatarLoading"
      :ok-text="'确定'"
      :cancel-text="'取消'"
    >
      <div class="avatar-upload">
        <a-upload
          v-model:file-list="avatarFileList"
          :before-upload="beforeAvatarUpload"
          :show-upload-list="false"
          accept="image/*"
        >
          <div class="upload-area">
            <a-avatar 
              :src="avatarPreview || userInfo?.avatar" 
              :size="100"
              class="preview-avatar"
            >
              {{ userInfo?.nickname?.charAt(0) || 'U' }}
            </a-avatar>
            <p>点击上传头像</p>
          </div>
        </a-upload>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/stores'
import { userApi, fileApi } from '@/api' // 添加 fileApi
import type { UserInfo, UserStats } from '@/types'

const userStore = useUserStore()

// 响应式数据
const userInfo = computed(() => userStore.userInfo)
const userStats = ref<UserStats>({
  joinDate: '',
  postCount: 0,
  likeCount: 0,
  viewCount: 0,
  userId: 0,
  commentCount: 0
})
const userPosts = ref<any[]>([])
const postsLoading = ref(false)
const updateLoading = ref(false)
const showAvatarModal = ref(false)
const avatarLoading = ref(false)
const avatarFileList = ref<any[]>([])
const avatarPreview = ref('')
const selectedAvatarFile = ref<File | null>(null) // 添加这一行来存储选中的文件

// 编辑表单
const editForm = reactive({
  nickname: '',
  email: '',
  bio: '',
  website: ''
})

// 表单验证规则
const editRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在2到20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ]
}

// 获取角色文本
const getRoleText = (role?: string) => {
  const roleMap: Record<string, string> = {
    'ADMIN': '管理员',
    'USER': '普通用户'
  }
  return roleMap[role || ''] || '未知'
}

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 重置表单
const resetForm = () => {
  if (userInfo.value) {
    editForm.nickname = userInfo.value.nickname
    editForm.email = userInfo.value.email
    editForm.bio = userInfo.value.bio || ''
    editForm.website = userInfo.value.website || ''
  }
}

// 更新个人信息
const handleUpdateProfile = async () => {
  if (!userInfo.value) return
  
  updateLoading.value = true
  
  try {
    const response = await userApi.updateUserInfo(userInfo.value.id, editForm)
    userStore.updateUserInfo(response.data)
    message.success('个人信息更新成功')
  } catch (error: any) {
    message.error(error.message || '更新失败')
  } finally {
    updateLoading.value = false
  }
}

// 头像上传前处理
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件')
    return false
  }
  
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过2MB')
    return false
  }
  
  // 存储选中的文件
  selectedAvatarFile.value = file
  
  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarPreview.value = e.target?.result as string
  }
  reader.readAsDataURL(file)
  
  return false // 阻止自动上传
}

// 更新头像
const handleAvatarUpdate = async () => {
  if (!selectedAvatarFile.value || !userInfo.value) return
  
  avatarLoading.value = true
  
  try {
    // 先上传头像文件
    const uploadResponse = await fileApi.uploadImage(selectedAvatarFile.value)
    
    // 使用返回的文件URL更新用户头像
    const avatarUrl = uploadResponse.data.filePath
    await userApi.updateAvatar(userInfo.value.id, avatarUrl)
    
    userStore.updateUserInfo({ avatar: avatarUrl })
    message.success('头像更新成功')
    showAvatarModal.value = false
    
    // 重置状态
    selectedAvatarFile.value = null
    avatarPreview.value = ''
    avatarFileList.value = []
  } catch (error: any) {
    message.error(error.message || '头像更新失败')
  } finally {
    avatarLoading.value = false
  }
}

// 加载用户数据
const loadUserData = async () => {
  if (!userInfo.value) return
  
  try {
    // 加载用户统计
    const statsResponse = await userApi.getUserStats(userInfo.value.id)
    userStats.value = statsResponse.data
    
    // 加载用户文章
    postsLoading.value = true
    const postsResponse = await userApi.getUserPosts(userInfo.value.id)
    userPosts.value = postsResponse.data.posts || []
  } catch (error) {
    console.error('加载用户数据失败:', error)
  } finally {
    postsLoading.value = false
  }
}

onMounted(() => {
  resetForm()
  loadUserData()
})
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.user-info-card {
  text-align: center;
  margin-bottom: 24px;
}

.user-avatar-section {
  margin-bottom: 24px;
}

.user-avatar {
  margin-bottom: 12px;
}

.change-avatar-btn {
  display: block;
  margin: 0 auto;
}

.user-details h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.user-details p {
  margin: 4px 0;
  color: #8c8c8c;
}

.username {
  font-weight: 500;
  color: #1890ff !important;
}

.stats-card {
  margin-bottom: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #1890ff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #8c8c8c;
}

.edit-form-card {
  margin-bottom: 24px;
}

.posts-card {
  margin-bottom: 24px;
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.post-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  transition: all 0.3s;
}

.post-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.post-content {
  flex: 1;
}

.post-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
}

.post-excerpt {
  margin: 0 0 8px 0;
  color: #8c8c8c;
  font-size: 14px;
}

.post-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #8c8c8c;
}

.post-actions {
  display: flex;
  gap: 8px;
}

.empty-posts {
  text-align: center;
  padding: 40px 0;
}

.avatar-upload {
  text-align: center;
}

.upload-area {
  cursor: pointer;
  padding: 20px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  transition: all 0.3s;
}

.upload-area:hover {
  border-color: #1890ff;
}

.preview-avatar {
  margin-bottom: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    padding: 16px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .post-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .post-actions {
    align-self: flex-end;
  }
}
</style>